package com.chml.filter;

import com.chml.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.MarkerManager;
import org.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;

/**
 * Created by chengmenglong on 2016/9/18.
 */
public class LoginInterceptor implements HandlerInterceptor {

    private FilterConfig config;
    @Resource
    private UserService userService;
    private static Logger logger = LogManager.getLogger();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuilder paramBuilder = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            paramBuilder.append(line);
        }
        logger.info(MarkerManager.getMarker("Request Body"),paramBuilder.toString());
        JSONObject param = new JSONObject(paramBuilder.toString());
        int uid = param.getInt("uid");
        String token = param.getString("access_token");
        if (userService.isValidRequest(uid, token)) {
            return true;
        }
        else {
            JSONObject ret = new JSONObject();
            ret.put("success", false);
            ret.put("msg", "登录校验失败，请重新登录");
            BufferedWriter writer = new BufferedWriter(response.getWriter());
            writer.write(ret.toString());
            writer.flush();
            writer.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
